package cn.tedu.tmall.front.mall.filter;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.pojo.po.UserStatePO;
import cn.tedu.tmall.common.pojo.security.CurrentPrincipal;
import cn.tedu.tmall.common.web.JsonResult;
import cn.tedu.tmall.front.mall.dao.cache.IUserCacheRepository;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>处理JWT的过滤器类，主要实现：</p>
 *
 * <ul>
 *     <li>尝试接收客户端提交的JWT</li>
 *     <li>尝试解析客户端提交的JWT</li>
 *     <li>将解析结果创建为Authentication并存入到SecurityContext</li>
 * </ul>
 */
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Value("${tmall.jwt.secret-key}")
    private String secretKey;
    @Autowired
    private IUserCacheRepository userCacheRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取本次请求的路径
        String requestURI = request.getRequestURI();
        // System.out.println(requestURI);

        // 对某些请求（不需要携带JWT的请求）直接放行
        if (requestURI.equals("/doc.html")
                || requestURI.equals("/swagger-resources")
                || requestURI.equals("/v2/api-docs")
                || requestURI.endsWith(".css")
                || requestURI.endsWith(".js")
                || requestURI.equals("/favicon.ico")
                || requestURI.equals("/users/login")) {
            // 放行
            // System.out.println("放行：" + requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println("尝试解析JWT的请求：" + requestURI);

        // 根据业内的惯例，JWT数据应该是请求头中名为Authorization的属性
        // 从请求头中获取JWT数据
        String jwt = request.getHeader("Authorization");
        System.out.println("客户端携带的JWT：" + jwt);

        // 检查是否获取到有效的JWT
        if (!StringUtils.hasText(jwt) || jwt.length() < 113) {
            // 没有获得有效的JWT，则放行，由后续的过滤器进行下一步处理
            filterChain.doFilter(request, response);
            return;
        }

        // 尝试解析JWT
        response.setContentType("application/json; charset=UTF-8");
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (SignatureException e) {
            String message = "非法访问（验证签名失败），本次访问已经被记录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            writer.close();
            return;
        } catch (MalformedJwtException e) {
            String message = "非法访问（数据格式错误），本次访问已经被记录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            writer.close();
            return;
        } catch (Throwable e) {
            String message = "操作失败，服务器忙，请稍后再试！【同学们，当你们看到这句时，应该在控制台查看异常的相关信息，并在处理JWT的过滤器中补充对此类异常的处理】";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_UNKNOWN, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            writer.close();
            return;
        }

        // 从解析结果中获取用户的身份信息
        Long userId = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        String remoteAddr = claims.get("remoteAddr", String.class);
        String userAgent = claims.get("userAgent", String.class);

        // 检查JWT是否存在盗用行为
        if (!remoteAddr.equals(request.getRemoteAddr())
                && !userAgent.equals(request.getHeader("User-Agent"))) {
            // JWT中记录的IP与浏览器信息，与本次请求中的IP与浏览器均不相同，则视为“盗用”
            // 放行，由后续的组件进行处理
            filterChain.doFilter(request, response);
            return;
        }

        // 从Redis中获取用户的状态数据
        UserStatePO userState = userCacheRepository.getUserState(userId);
        System.out.println("从Redis中读取用户的状态数据：" + userState);
        if (userState == null) {
            // 没有在Redis中获得有效的用户状态，则视为“未通过认证”，放行，由后续的过滤器进行下一步处理
            filterChain.doFilter(request, response);
            return;
        }

        // 检查账号的启用状态
        if (userState.getEnable() != 1) {
            userCacheRepository.deleteUserState(userId);
            String message = "您的账号已经被禁用，将强制下线！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED_DISABLED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            writer.close();
            return;
        }

        // 对Redis中的用户状态数据进行“续期”
        userCacheRepository.renewal(userId);

        // 准备当事人数据
        CurrentPrincipal principal = new CurrentPrincipal();
        principal.setId(userId);
        principal.setUsername(username);

        // 准确权限列表，需要是符合框架要求的数据格式，即Collection<? extends GrantedAuthority> authorities
        String authoritiesJsonString = userState.getAuthoritiesJsonString();
        List<String> stringList = JSON.parseArray(authoritiesJsonString, String.class);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String authority : stringList) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
            authorities.add(grantedAuthority);
        }

        // 将解析得到的用户身份信息创建为Authentication并存入到SecurityContext
        Authentication authentication
                = new UsernamePasswordAuthenticationToken(principal, null, authorities);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        System.out.println("已经将认证信息存入到SecurityContext，当事人：" + principal);

        // 放行
        filterChain.doFilter(request, response);
    }

}
